// pages/envelopes-get/envelopes-get.js
const apiurl = require('../../config').apiurl;
import {
  Pulibc
} from '../../models/public.js'
const pulibc = new Pulibc();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    info: {},
    ro_id:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.getEnvelopes();
  },
  //  第一次领取红包
  getRedPost() {
    let key = wx.getStorageSync('key');
    let url = apiurl + '/redenvelopes/redpost'
    wx.request({
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      url: url,
      method: 'POST',
      data: {
        key
      },
      success: data => {
        console.log('redPost', data.data);
        // wx.setStorageSync('ifShare', 0);

        let ro_id=data.data.ro_id;
        if (data.data.code == 200) {
          wx.redirectTo({
            url: '../envelopes/envelopes?ro_id=' + ro_id
          })
        } else if (data.data.code == 400){
          let msg = data.data.datas.error
          wx.showModal({
            title: '提示',
            content: msg,
          })
        }
      }
    })
  },

  // 获取红包信息
  getEnvelopes() {
    let key = wx.getStorageSync("key")
    let url = apiurl + '/redenvelopes/index'
    wx.request({
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      url: url,
      data: {
        key
      },
      method: 'POST',
      success: res => {

        console.log(res)
        if (res.data.code == 200) {
          let ro_id=res.data.datas.ro_id;
          if (ro_id){
            wx.redirectTo({
              url: '../envelopes/envelopes?ro_id=' +ro_id
            })
          }else{
            let info = res.data.datas.info
            this.setData({
              info
            })
          }
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (wx.getStorageSync("key") == false) {
      wx.navigateTo({
        url: "../register/register"
      })
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})